<?php
namespace App\Admin\Controllers\Products;

use App\Importer\Products\SkuVariant\Importer;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductVariant;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class SkuVariantUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        return view("products.sku-variant.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new Importer(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            foreach($data as $row){
                $count++;
                $plat = $row[0] ? trim($row[0]) : '';
                $_country = $row[1] ? trim($row[1]) : '';
                $classify = $row[2] ? trim($row[2]) : '';
                $parentStandard = $row[3] ? trim($row[3]) : '是';
                $parentAccount = $row[4] ? trim($row[4]) : '';
                $aPlusAccount = $row[5] ? trim($row[5]) : '';
                if(!$plat || !$_country || !$classify || !$parentStandard || !$parentAccount || !$aPlusAccount){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $country = strtoupper($_country);
                $key = $plat.'_'.$country.'_'.$classify;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $platId = SysPlat::getSysPlatId($plat);
                if(!$platId){
                    $errors[$count] = $plat.'系统不存在';
                    continue;
                }
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = $classify.'品类不存在';
                    continue;
                }
                if(!in_array($parentStandard,ProductVariant::$_parentStandard)){
                    $errors[$count] = $parentStandard.'父体是否合规字段录入错误，请选择'.implode('、',ProductVariant::$_parentStandard);
                    continue;
                }
                $parentAccounts = ProductVariant::getAccountIdArrByAccountStr($parentAccount);
                if(!$parentAccounts){
                    $errors[$count] = $parentAccount.'格式有误，未匹配到数据';
                    continue;
                }
                $aPlusAccounts = ProductVariant::getAccountIdArrByAccountStr($aPlusAccount);
                if(!$aPlusAccounts){
                    $errors[$count] = $aPlusAccount.'格式有误，未匹配到数据';
                    continue;
                }
                DB::beginTransaction();
                $re = ProductVariant::query()
                    ->firstOrNew(['plat_id' => $platId,
                        'country_id' => $countryId,
                        'classify_id' => $classifyId]);
                $re->parent_standard = array_search($parentStandard,ProductVariant::$_parentStandard);
                $re->parent_account = $parentAccounts;
                $re->aplus_account = $aPlusAccounts;
                $flag = $re->save();
                if($flag){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
